package com.openlogic.common.datasource.listener;

import java.sql.ResultSet;

import org.noear.solon.annotation.Component;
import org.noear.solon.core.event.AppLoadEndEvent;
import org.noear.solon.core.event.EventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mybatisflex.core.FlexGlobalConfig;
import com.mybatisflex.core.datasource.FlexDataSource;
import com.openlogic.common.core.constants.DataSourceConstant;
import com.openlogic.common.core.constants.DataSourceConstant.Details;
import com.openlogic.common.datasource.config.MybatisFlexConfig;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

/**
 * @ClassName: AppLoadEndEventListener
 * @Description: 应用 Bean加载完成事件
 * @author weiyongpeng
 * @date 2025年2月3日 上午10:15:19
 */
@Component
public class AppLoadEndEventListener implements EventListener<AppLoadEndEvent> {

	private static final Logger log = LoggerFactory.getLogger(AppLoadEndEventListener.class);

	@Override
	public void onEvent(AppLoadEndEvent event) throws Throwable {
		event.app().context().beanForeach((k, v) -> {
			// 如果引入了数据源，配置一下 Mybatis-Flex
			if (DataSourceConstant.DATA_SOURCE_MASTER.equals(k)) {
				event.app().context().beanMake(MybatisFlexConfig.class);
			}
		});
		log.info("项目加载完，执行...");
		FlexDataSource dataSource = FlexGlobalConfig.getDefaultConfig().getDataSource();
		ResultSet rs = dataSource.getConnection().createStatement().executeQuery(DataSourceConstant.SELECT_SOURCE);
		while (rs.next()) {
			String name = rs.getString(Details.SLAVE.getCode());
			String username = rs.getString(Details.USERNAME.getCode());
			String password = rs.getString(Details.PASSWORD.getCode());
			String url = rs.getString(Details.URL_PREPEND.getCode())
					.concat(rs.getString(Details.URL_APPEND.getCode()) == null ? ""
							: rs.getString(Details.URL_APPEND.getCode()));
			String driver = rs.getString(Details.DRIVER_CLASS_NAME.getCode());
			HikariConfig hikariConfig = new HikariConfig();
			hikariConfig.setJdbcUrl(url);
			hikariConfig.setDriverClassName(driver);
			hikariConfig.setPassword(password);
			hikariConfig.setUsername(username);
			dataSource.addDataSource(name, new HikariDataSource(hikariConfig));
		}
	}

}
